<?php
abstract class Libs{
	abstract protected function init();
	abstract protected function main();
	
	public function run(){
		$this->init();
		$this->before();
		$this->main();
		$this->after();
	}
	
	public function before(){
		if(!empty($this->db)){
			$db_arr = include_once DIR_CONF.'db.conf.php';
			require_once DIR_CLASS.'Mysql.class.php';
            $this->db_arr = explode(',', $this->db);
            foreach($this->db_arr as $v){
                if(!empty($v)){
                    $db = $db_arr[$v];
					$prefix = $v.'_prefix';
			        $this->$v = new Mysql($db['host'], $db['name'], $db['pass'], $db['datebase'], $db['prefix']);
					$this->$prefix = $db['prefix'];
                }
            }
		}
	}
	
	public function after(){
		global $file;
		if(!empty($this->tpl)){
			$this->tpl_include($this->tpl);
		}else if($this->_json_data){
			echo json_encode($this->_json_data);
		}
	}
	
	public function tpl_include($tpl){
		global $file;
		$t_arr = explode('_', $tpl);
			
		$tplname = '';
		foreach($t_arr as $v){
			$tplname .= htmlspecialchars(ucwords(strtolower($v)), ENT_QUOTES, 'UTF-8').'_';
		}
		$tplname = substr($tplname, 0, -1);
		$tplname = explode('/', $tplname);
		$tpl_arr_count = count($tplname);
		$tplname[$tpl_arr_count - 1] = ucwords(strtolower($tplname[$tpl_arr_count - 1]));
		$tplname = implode('/', $tplname);
		if(file_exists(DIR_TPL.$file.$tplname.'.tpl.php')){
			foreach($this as $k => $v){
				$$k = $v;
			}
			require DIR_TPL.$file.$tplname.'.tpl.php';
		}else {
			if(DEBUG){
				exit('模版文件: '.DIR_TPL.$file.$tplname.'.tpl.php 不存在');
			}else {
				header('HTTP/1.1 404 Not Found'); 
				header("status: 404 Not Found"); 
			}
		}
	}
}
